package ink.ykb.actDemo.interceptors;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import ink.ykb.actDemo.util.Constant;
import ink.ykb.actDemo.util.HttpRequestLocal;

public class LoginInterceptor implements HandlerInterceptor{

	private HttpRequestLocal httpRequestLocal;

	public LoginInterceptor(HttpRequestLocal httpRequestLocal) {
		super();
		this.httpRequestLocal = httpRequestLocal;
	}

	private List<String> uriList = new ArrayList<>();
	
	//需要过滤的访问地址
	{
		uriList.add("/login");
		uriList.add("/error");
	}
	
	private  boolean containsURI() {
		String requestURI = httpRequestLocal.getRequestURI();
		for (String uri : uriList) {
			if(requestURI.indexOf(uri) == 0) {
				return true;
			}
		}
		return false;
	}
	
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		httpRequestLocal.set(request);
		
		if(!containsURI()) {
				Integer userId = (Integer)httpRequestLocal.getSessionValue(Constant.SESSION_USER_ID);
				if(userId == null){
					response.sendRedirect(httpRequestLocal.getAppURL()+"/login");
					return false;
				}
		}
		
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	
}
